﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PagedList;
using ThesisSystem.DAL;
using ThesisSystem.Models;
using ThesisSystem.ViewModels;
using System.Web.Security;

namespace ThesisSystem.Controllers
{
    [Authorize]
    public class ThesesController : Controller
    { 
        #region Index & Details
        private ThesisSystemEntities db = new ThesisSystemEntities();

        //
        // GET: /Theses/
       
        public ActionResult Index()
        {
            var userKey = new Guid(Membership.GetUser().ProviderUserKey.ToString());
            ThesisSearchView thesis = db.ThesisSearchViews.Where(t => t.UserID == userKey).SingleOrDefault();
            if (thesis != null)
            {
                 return View(thesis);
            }
            else
            {
                var redirectPage = new RedirectPage
                {
                    ActionName = "Create",
                    ControllerName = "Theses",
                    Msg = "您还未添加论文，请添加论文信息！"
                };

                return RedirectToAction("RedirectPage", redirectPage);
            }
        }

        //
        // GET: /Theses/Details/5

        public ActionResult Details()
        {
            var userKey = new Guid(Membership.GetUser().ProviderUserKey.ToString());
            ThesisSearchView thesis = db.ThesisSearchViews.Where(t => t.UserID == userKey).SingleOrDefault();
            if (thesis != null)
            {
            return View(thesis);
            }
            else
            {
                var redirectPage = new RedirectPage
                {
                    ActionName = "Create",
                    ControllerName = "Theses",
                    Msg = "未有论文信息，请先添加论文信息！"
                };

                return RedirectToAction("RedirectPage", redirectPage);
            }
        }
        #endregion

        public ActionResult Tails(int id)
        {
            var thesisview = db.ThesisSearchViews.Find(id);
            return View(thesisview);

        }
        #region 添加论文信息   
        //
        // GET: /Theses/Create
        public ActionResult Create()
        {

            //论文上传时间自动获取
            var userKey = new Guid(Membership.GetUser().ProviderUserKey.ToString());
            var thesis = db.Theses.Where(t => t.UserID == userKey).SingleOrDefault();
            if (thesis != null)
            {
                var redirectPage = new RedirectPage
                {
                    ActionName = "Details",
                    ControllerName = "Theses",
                    Msg = "论文基本信息已存在，请检查论文附件是否已上传！"
                };

                return RedirectToAction("RedirectPage", redirectPage);
            }
            else
            {
                
                var thesisType = db.ThesisTypes.OrderBy(m => m.TypeName);
                ViewBag.ThesisType = new SelectList(thesisType, "TypeName", "TypeName");
                //thesis.UploadDate = DateTime.Now;
                return View(thesis);
            }
        }

        //
        // POST: /Theses/Create

        [HttpPost]
        public ActionResult Create(Thesis thesis)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    thesis.UserID = new Guid(Membership.GetUser().ProviderUserKey.ToString());
                    //thesis.UploadDate = DateTime.Now;
                    db.Theses.Add(thesis);
                    db.SaveChanges();
                    return RedirectToAction("Upload", new { id = thesis.ThesisID });
                    //  return View("Upload");
                }
            }
            catch (Exception)
            {
                // throw ee.InnerException;
                //ViewBag.Error = de.Message;
            }
            var thesisType = db.ThesisTypes.OrderBy(m => m.TypeName);
            ViewBag.ThesisType = new SelectList(thesisType, "TypeName", "TypeName");
            return View(thesis);
        }
        #endregion

        # region  指导论文列表
        public ActionResult DirectList()
        {
            
            return View();
        }
        #endregion
        #region 开始评审
        public ActionResult Star()
        {
            return View();
        }
        #endregion
        #region 评卷
        public  ActionResult Mark()
        {


            var thesis = db.Targets.Where(t=>t.TypeName=="理科").ToList();
            return View(thesis);
        }
        #endregion

        #region 自动跳转
        public ActionResult RedirectPage(RedirectPage redirectPage)
        {

            return View(redirectPage);
        }
        #endregion  
        #region 信息编辑
        // GET: /Theses/Edit/5
     
        public ActionResult Edit()
        {
            var userKey=new Guid(Membership.GetUser().ProviderUserKey.ToString());
            Thesis thesis = db.Theses.Where(t => t.UserID == userKey).SingleOrDefault();
            if (thesis != null)
            {
                var thesisType = db.ThesisTypes.OrderBy(m => m.TypeName).ToList();
                ViewBag.ThesisType = new SelectList(thesisType, "TypeName", "TypeName");
                return View(thesis);
            }
            else
            {
                var redirectPage = new RedirectPage
                {
                    ActionName = "Create",
                    ControllerName = "Theses",
                    Msg = "未有论文信息，请先添加论文信息！"
                };

                return RedirectToAction("RedirectPage", redirectPage);
            }
        }

        public ActionResult  teacherknow()
        {
            return View();
        }
        //
        // POST: /Theses/Edit/5

        [HttpPost]
        public ActionResult Edit(Thesis thesis)
        {
            if (ModelState.IsValid)
            {
                db.Entry(thesis).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Details", new { id=thesis.ThesisID});
            }
            else
            {
                return View(thesis);
            }

        }
        #endregion

        #region 删除论文信息
        // GET: /Theses/Delete/5

        public ActionResult Delete(int id)
        {
            Thesis thesis = db.Theses.Find(id);
            return View(thesis);
        }

        //
        // POST: /Theses/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {

            Thesis thesis = db.Theses.Find(id);
           
            var paththesis = long.Parse(thesis.StudentID);
            string filepath = AppDomain.CurrentDomain.BaseDirectory + "Content/upload/" + thesis.UploadDate.ToString("yyyy-MM") + "/" + paththesis + "/" + thesis.FileName;
            if (System.IO.File.Exists(filepath))
            {
                System.IO.File.Delete(filepath);
            }

            db.Theses.Remove(thesis);
            db.SaveChanges();

            return RedirectToAction("Index");
        }
        #endregion

    #region  移除文件
        //GET: These/Rmove/id
        public ActionResult Remove(int id)
        {
            Thesis thesis = db.Theses.Find(id);
            return View(thesis);
        }

        [HttpPost, ActionName("Remove")]
        public ActionResult RemoveConfirmed(int id)
        {
            Thesis thesis = new Thesis();
            thesis = db.Theses.Find(id);
            // var paththesis = db.Theses.SingleOrDefault(m => m.ThesisID == id).StudentID.ToString();
            var paththesis = long.Parse(thesis.StudentID);
            //找到文件保存路径
            string filepath = AppDomain.CurrentDomain.BaseDirectory + "Content/upload/" + thesis.UploadDate.ToString("yyyy-MM") + "/" + paththesis + "/" + thesis.FileName;
            if (System.IO.File.Exists(filepath))
            {
                System.IO.File.Delete(filepath);//判断，如果文件存在则删除
                thesis.FileName = "文件已移除"; 
                thesis.FileSize = "文件已移除";
                //thesis.UploadDate = DateTime.Parse("0");
            }
            //db.Theses.Remove(thesis);
            db.Entry(thesis).State = EntityState.Modified;
            db.SaveChanges();

            return RedirectToAction("Upload", new { id = thesis.ThesisID });
        }
     #endregion
        #region 文件上传
        // GET: These/Upload/id
        public ActionResult Upload()
        {
            var userKey = new Guid(Membership.GetUser().ProviderUserKey.ToString());
            Thesis thesis = db.Theses.Where(t => t.UserID == userKey).SingleOrDefault();
            if (thesis != null)
            {
                if (string.IsNullOrEmpty(thesis.FileName) || thesis.FileSize.Equals("文件已移除"))
                {
                    return View(thesis);
                }
                else
                {
                        var redirectPage = new RedirectPage
                        {
                            ActionName = "Edit",
                            ControllerName = "Theses",
                            Msg = "论文已存在，如需重新上传，请先移除文件！"
                        };

                    return RedirectToAction("RedirectPage", redirectPage);
                }
            }
            else
            {
                var redirectPage = new RedirectPage
                {
                    ActionName = "Create",
                    ControllerName = "Theses",
                    Msg = "未有论文信息，请先添加论文信息！"
                };

                return RedirectToAction("RedirectPage", redirectPage);
            }
        }

        // Post: These/Upload/id
        [HttpPost, ActionName("Upload")]
        public ActionResult UploadConfirmed()
        {
            var userKey = new Guid(Membership.GetUser().ProviderUserKey.ToString());
            Thesis thesis = db.Theses.Where(t => t.UserID == userKey).SingleOrDefault();
            String[] suffix = { ".doc", ".docx" };//可上传的拓展名
            foreach (string item in Request.Files)
            {
                var paththesis = long.Parse(thesis.StudentID);
                HttpPostedFileBase file = Request.Files[item] as HttpPostedFileBase;
                if (file == null && file.ContentLength == 0)
                    continue;
                //判断Upload文件夹是否存在，不存在就创建
                string path = Server.MapPath("~/Content/upload/" + DateTime.Now.ToString("yyyy-MM") + "/" + paththesis + "/");
              
                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);
                }
                path = AppDomain.CurrentDomain.BaseDirectory + "Content/upload/" + DateTime.Now.ToString("yyyy-MM") + "/" + paththesis + "/";
                //获取上传的文件名
                string fileName = Path.GetFileName(file.FileName);
                string filePath = Path.Combine(path, fileName);
                //限制上传文件的类型
                Boolean uploadtrue = false;
                foreach (var m in suffix as String[])
                {
                    if (Path.GetExtension(fileName).ToLower() == m)
                    {
                        uploadtrue = true;
                        break;
                    }
                }
                if (uploadtrue == false)
                {
                    var redirectPage = new RedirectPage
                    {
                        ActionName = "Upload",
                        ControllerName = "Theses",
                        Msg = "不能上传这种类型的文件,请重新上传！"
                    };

                    return RedirectToAction("RedirectPage", redirectPage);
                }
                else
                {

                    file.SaveAs(filePath);


                }

                string sizekb = "";
                FileInfo filesize = new FileInfo(filePath);
                ViewBag.FileSize = filesize;
                // fs = filesize.Length/1024;
                sizekb = Convert.ToString(Convert.ToDouble(filesize.Length) / 1024) + "KB";
                if (sizekb != "")
                {
                    //thesis = db.Theses.SingleOrDefault(m => m.ThesisID == id);
                    thesis.FileName = fileName;
                    thesis.FileSize = sizekb;
                    thesis.UploadDate = DateTime.Now;
                    db.Entry(thesis).State = EntityState.Modified;
                    db.SaveChanges();

                }

            }
    

            var redirectPage1 = new RedirectPage
            {
                ActionName = "Details",
                ControllerName = "Theses",
                Msg = "文件上传成功！"
            };

            return RedirectToAction("RedirectPage", redirectPage1);

        }
        #endregion
        #region 文件下载

        public FileStreamResult DownLoad(int id)
        {

            var thesis = db.Theses.SingleOrDefault(m => m.ThesisID == id);
            var paththesis = long.Parse(thesis.StudentID);
            var uploadTime = thesis.UploadDate.ToString("yyyy-MM");
            string path = Server.MapPath("~/Content/upload/" + uploadTime + "/" + paththesis + "/" + thesis.FileName);
            if (System.IO.File.Exists(path))
            {
                return File(new FileStream(path, FileMode.Open), "text/plain", thesis.FileName);
            }
            else
            {
                return null;
            }

        }


        #endregion

   #region 测试
//        public ActionResult test()
//        {

//            IDictionary<string, string> searchConditions = new Dictionary<string, string>();

//            if (this.Request.Form.AllKeys.Length > 0)
//            {
//                searchConditions.Add("StudentID", Request["StudentID"]);
//                searchConditions.Add("ThesisTitle", Request["ThesisTitle"]);
//            }
//            else
//            {
//                object values = null;

//                if (this.TempData.TryGetValue("SearchConditions", out values))
//                {
//                    searchConditions = values as Dictionary<string, string>;
//                }
//            }

//            this.TempData["SearchConditions"] = searchConditions;

//            string studentName = GetSearchConditionValue(searchConditions, "StudentID");
//            string Title = GetSearchConditionValue(searchConditions, "ThesisTitle");

//            ThesisSystemEntities db = new ThesisSystemEntities();
//            var result = (from s in db.Theses
//                          where (string.IsNullOrEmpty(studentName) || s.StudentID.StartsWith(studentName))
//                         && (string.IsNullOrEmpty(Title) || s.ThesisTitle.StartsWith(Title))
//                          select s).ToList();
//            this.ViewData.Model = result;
//            return View();
//        }

//        private static string GetSearchConditionValue(IDictionary<string, string> searchConditions, string key)
//        {
//            string tempValue = string.Empty;

//            if (searchConditions != null && searchConditions.Keys.Contains("ThesisTitle"))
//            {
//                searchConditions.TryGetValue(key, out tempValue);
//            }

//            return tempValue;
//        }
       #endregion

        #region 论文查询
        //GET:/theses/Search
        //public ActionResult Search(string searchString,string currentFilter,int? page,ThesisSearch thesisSearch)
        public ActionResult Search(int? page, ThesisSearch thesisSearch)
        {
            // var thesis = db.Theses.Where(v => v.ThesisID != 0);
            //  var thesis=db.Theses.Include(s=>s.Student).Where((v => v.ThesisID != 0));
            var thesis = db.ThesisSearchViews.ToList();
            if (!string.IsNullOrEmpty(thesisSearch.ThesisTitle))
            {
                //根据关键字筛选出论文标题
                thesis = thesis.Where(t => t.ThesisTitle.ToUpper().Contains(thesisSearch.ThesisTitle.ToUpper())).ToList();
            }
            if (!string.IsNullOrEmpty(thesisSearch.Name))
            {
                //根据关键字筛选出论文作者
                thesis = thesis.Where(t => t.Name.ToUpper().Contains(thesisSearch.Name.ToUpper())).ToList();
            }
            if (!string.IsNullOrEmpty(thesisSearch.StudentID))
            {
                //根据关键字筛选出论文作者学号
                thesis = thesis.Where(t => t.StudentID.ToUpper().Contains(thesisSearch.StudentID.ToUpper())).ToList();
            }
            if (!string.IsNullOrEmpty(thesisSearch.StudyProfessional))
            {
                //根据关键字筛选出论文作者所学专业
                thesis = thesis.Where(t => t.StudyProfessional.ToUpper().Contains(thesisSearch.StudyProfessional.ToUpper())).ToList();
            }
            if (!string.IsNullOrEmpty(thesisSearch.ThesisType))
            {
                //根据关键字筛选出论文的类型
                thesis = thesis.Where(t => t.ThesisType.ToUpper().Contains(thesisSearch.ThesisType.ToUpper())).ToList();
            }
            if (!string.IsNullOrEmpty(thesisSearch.Department))
            {
                thesis = thesis.Where(t => t.DepartmentName.ToUpper().Contains(thesisSearch.Department.ToUpper())).ToList();
            }
            if (!string.IsNullOrEmpty(thesisSearch.ReviewStatus))
            {
                //根据关键字筛选出论文评审状态
                thesis = thesis.Where(t => t.StudyProfessional.ToUpper().Contains(thesisSearch.StudyProfessional.ToUpper())).ToList();
            }

            var thesisType = db.ThesisTypes.OrderBy(m => m.TypeName);
            ViewBag.ThesisType = new SelectList(thesisType, "TypeName", "TypeName");
            ViewBag.Current = thesisSearch;
            int pageSize = 2;//定义每页显示的记录数
            int pageIndex = (page ?? 1) - 1;
            return View(thesis.ToPagedList(pageIndex, pageSize));
        }
        #endregion
        protected override void Dispose(bool disposing)
        {

            db.Dispose();
            base.Dispose(disposing);
        }
    }
}